<?php
namespace app\gym\controller;
use app\common\controller\AdminBase;
/*私教合同管理*/
class GymPtOrder extends AdminBase{
	protected $beforeActionList = [
        'before_index'=>['only'=>'index'],
    ];
	function _initialize() {
		parent::_initialize();  
    }
	function index(){
		$shop_id=sp_get_current_shop_id();
		$this->assign("ptlist",db("GymEmployee")->where("status=1 and coash_type!=2 and shop_id=$shop_id")->select());
		echo $this->fetch();
	}	
	function add(){
		$shop_id=sp_get_current_shop_id();
		$this->assign("courses",db("GymCourse")->field("id,name,price")->where("status=1 and shop_id=$shop_id and type=1")->select());
		$this->assign("pts",db("GymEmployee")->field("id,name")->where("status=1 and shop_id=$shop_id and type=3")->select());
		echo $this->fetch();
	}
	function add_post(){
		if(empty(input("member_id"))){
			return $this->ajax_error("请选择会员");
		}
		if(request()->isPost()){
		    $pt_id = input("pt_id", 0);
		    $price = input("price",  0);
		    $shop_id = sp_get_current_shop_id();
		    if (empty($pt_id)) {
		        $this->ajax_error("请选择pt");
            }
				$data=array(
									'shop_id'=>$shop_id,
									'course_name'=>input('course_name'),
									'course_id'=>input('course_id'),
									'course_count'=>input('course_count'),
									'start_date'=>input('start_date'),
									'end_date'=>input('end_date'),
									'order_no'=>time().rand(1000,9999),
									'member_id'=>input('member_id'),
									'pt_id'=>$pt_id,
									'surplus'=>input('course_count'),
									"descs"=>input('descs'),
									"price"=>$price,
									"type"=>1
									);
		//新增									
		$order_id=db('GymPtOrder')->insertGetId($data);
		db("GymPtOrder")->where("id=$order_id")->setField(array('old_order_id'=>$order_id));
		//新增历史
            $data['admin_id'] = sp_get_current_admin_id();
		$order_id_1=db('GymPtOrderHistory')->insertGetId($data);
		db("GymPtOrderHistory")->where("id=$order_id")->setField(array('old_order_id'=>$order_id_1));
		//教练业绩
		$this->employeeAchievement($price, $pt_id, $shop_id);

		action("smallapp/PTFollow/after_pt_deal",['pt_order_id'=>$order_id]);						
		return	$this->ajax_success("成功!");	
		}else{
			$this->ajax_error("非法操作!");
		}
	}

	/*合同转让*/
	function transfer(){
		$model=db("GymPtOrder")->field("id,member_id,course_name,course_count,price,pt_id,end_date,start_date,surplus,order_no")->find(input("id"));
		$model['member_name']=db("GymMember")->where("id=".$model['member_id'])->value("concat(name,'--',mobile)");
		$model['pt_name']=db("GymEmployee")->where("id=".$model['pt_id'])->value("name");
		$model['order_date']=db("GymPtFollow")->where("member_id=".$model['member_id']." and type=2 and TO_DAYS(order_date)>=TO_DAYS(now())")->value("order_date");
		$this->assign("model",$model);
		echo $this->fetch();
	}
	/*合同转让*/
	function transfer_post(){
	    $shop_id = sp_get_current_shop_id();
		if(empty(input("member_id"))){
			return $this->ajax_error("请选择会员");
		}
		if(request()->isPost()){
			$order_no=time().rand(1000,9999);
			//旧合同
			$old_order=db("GymPtOrderHistory")->where("order_no='".input("old_order_no")."'")->find();
			//修改原合同	
			db("GymPtOrder")->where("id=".input("old_order_id"))->setField(array("member_id"=>input("member_id"),"order_count"=>0,"follow_count"=>0,"last_course_time"=>null,"last_order_time"=>null,"last_order_id"=>null,"order_no"=>$order_no,"type"=>2));
			//删除已有跟进
			db("GymPtFollow")->where("pt_order_id=".input("old_order_id"))->delete();
			//新增跟进
			action("smallapp/PTFollow/after_pt_deal",['pt_order_id'=>input("old_order_id")]);
			//新增历史记录	
			$old_order["old_order_id"]=$old_order['id'];	
			$old_order['type']=2;
			$old_order['member_id']=input("member_id");
			$old_order['price']=input("price",0);
			$old_order['descs']=input("descs","转课");
			$old_order['order_no']=$order_no;
			$old_order['admin_id'] = sp_get_current_admin_id();
			unset($old_order['id']);

			db("GymPtOrderHistory")->insert($old_order);

            //教练业绩（442 【小型】私教课转让收费算流水，不算pt的业绩）
//            $this->employeeAchievement($old_order['price'], $old_order["pt_id"], $shop_id);

			return	$this->ajax_success("成功!");	
		}else{
			$this->ajax_error("非法操作!");
		}
	}
	/*退课*/
	function withdraw(){
		$model=db("GymPtOrder")->field("id,member_id,course_name,course_count,price,pt_id,end_date,start_date,surplus")->find(input("id"));
		$model['member_name']=db("GymMember")->where("id=".$model['member_id'])->value("concat(name,'--',mobile)");
		$model['pt_name']=db("GymEmployee")->where("id=".$model['pt_id'])->value("name");
		$model['order_date']=db("GymPtFollow")->where("member_id=".$model['member_id']." and type=2 and TO_DAYS(order_date)>=TO_DAYS(now())")->value("order_date");
		$this->assign("model",$model);
		echo $this->fetch();
	}
	
	/*退课*/
	function withdraw_post(){
		if(request()->isPost()){
			//原订单号
			$old_order_no=db("GymPtOrder")->where("id='".input("old_order_id")."'")->value("order_no");
			//原订单
			$old_order=db("GymPtOrderHistory")->where("order_no='$old_order_no'")->find();	
			$old_order['order_no']=time().rand(1000,9999);
			$old_order['type']=3;
			$old_order['status']=0;
			$old_order['price']=(0-input("price",0));
			$old_order['descs']=input("descs","退课");
			unset($old_order['id']);
            $old_order['admin_id'] = sp_get_current_admin_id();
			db("GymPtOrderHistory")->insert($old_order);
			
			//删除现有订单
			db("GymPtOrder")->where("id='".input("old_order_id")."'")->delete();
			//删除已有跟进
			db("GymPtFollow")->where("pt_order_id=".input("old_order_id"))->delete();
            //教练业绩
            $this->employeeAchievement($old_order['price'], $old_order["pt_id"], $old_order["shop_id"]);
			
		return	$this->ajax_success("成功!");	
		}else{
			$this->ajax_error("非法操作!");
		}
	}
	
	/*修改员工信息*/
	function edit(){
		$id=input("id",0);
		$this->assign("model",db("GymPtOrder")->where("id=$id")->find());
		echo $this->fetch();			
	}
	function edit_post(){
		$id=input("id");
		db('GymPtOrder')->where("id=$id")->update(array(
						"name"=>input("name"),
						"price"=>input("price"),
						"descs"=>input("descs"),
						"type"=>input("type"),
						));
		$this->ajax_success("成功！");	
	}
	
	function delete(){
		if(request()->isPost()){
			$id=input("id");
			db("GymPtOrder")->where("id=$id")->delete();
			$this->ajax_success("成功");
		}else{
			$this->ajax_error("非法操作！");
		}
	}
	
	function ajax_index(){
		$this->ajax($this->_ajax_index());
	}
	/*获取会员 数据*/
	function ajax_seach_data(){
		$shop_id = sp_get_current_shop_id();
		$q = input("q","x");
		$a = input("a", 0); //操作类型 1：转让
        $member_id = input("member_id/d", 0);
        $where = array("o.shop_id" => $shop_id, "o.is_delete" => 0, "m.name|m.mobile|o.card_no" => array("like", "%{$q}%"));
        if (!empty($a)) {
            $where["o.gym_member_id"] = array("neq", $member_id);
        }
		$list = db("gym_order")->alias("o")
            ->join("m_gym_member m", "o.gym_member_id = m.id", "left")
            ->where($where)
            ->field("m.id, CONCAT(m.name, '--', m.mobile, \"--\", o.gym_card_name) as text")
            ->select();
//		$list=db("GymMember")->alias("a")->fetchsql(FALSE)->join([["m_gym_order b","a.id=b.gym_member_id","left"]])->where(" a.shop_id=$shop_id and b.shop_id=$shop_id and ( a.name like '%$q%' or a.mobile like '%$q%' or b.card_no like '%$q%')")->field("a.id,CONCAT(a.name,'--',a.mobile, \"--\",b.gym_card_name) as text")->select();
//		header('Content-Type:application/json;charset=utf-8');
//		exit(json_encode($list,TRUE));
        $this->ajax($list);
	}
	
	///////////////////////////////////////////////////////////////////////////////////
	/**
	 * 权限菜单
	 **/
	function before_index(){
		$auth_group=sp_get_auth_menu_3("10061003");
		$this->assign("menus",$auth_group);
	}
	
	/*列表数据*/
	private function _ajax_index(){
		$shop_id=sp_get_current_shop_id();
		$card_no=input("card_no");
		$query=array(
					 'member_name'=>array("field" =>"c.name","operator" =>"="),
					 'mobile'=>array("field" =>"c.mobile","operator" =>"="),
					 'pt_id'=>array("field" =>"b.id","operator" =>"="),
					);
		$draw=input("draw",0)+1;//请求时间		 
		$where_and=join(" and ",sp_get_param_sql(request()->isPost(),$query));
		if(!empty($shop_id)){
			$where_and.=" and a.shop_id=$shop_id";
		}
		if(!empty($card_no)){
			$member_ids=db("GymOrder")->where("card_no='$card_no' and shop_id=$shop_id and is_delete=0")->column("member_id");
			if(!empty($member_ids)){
				$member_ids=implode(",", $member_ids);
				$where_and.=" and c.id in($member_ids)";	
			}
		}
		$field="a.id,a.course_name,a.status,a.type,a.course_count,a.price,a.surplus,a.end_date,c.name as member_name,c.mobile,b.name as pt_name,'' as card_no";
		$total=db("GymPtOrder")->alias("a")->join([["m_gym_employee b","a.pt_id=b.id","left"],["m_gym_member c","a.member_id=c.id","left"]])->where($where_and)->fetchsql(FALSE)->count(1);
		$list=db("GymPtOrder")->alias("a")->field($field)->join([["m_gym_employee b","a.pt_id=b.id","left"],["m_gym_member c","a.member_id=c.id","left"]])->where($where_and)->order("a.id desc")->limit($this->get_limit())->fetchsql(FALSE)->select();
		return array('pageData'=>$list,'total'=>$total,"draw"=>$draw);
	}
}
